<?php
/**
 * Plugin Administration.
 *
 * @package WP cr mobile
 */
class CRMobile_Admin
{
    const LICENSE_KEY = 'D84A-42B6-AE28-952A';

    /**
     * Constructor
     */
    public function __construct()
    {
        add_action('admin_menu', array(&$this,'registerMenu'));
        add_action('admin_enqueue_scripts', array($this, 'scripts'));
    }

    /**
     * Register the Admin.
     */
    public function registerMenu()
    {
        add_options_page(
            'WP cr mobile Options',
            'WP cr mobile',
            'can_access_wp_cr_mobile',
            CRMobile::PLUGIN_SLUG,
            array(&$this, 'optionsPage')
        );
    }

    /**
     * Load CSS and JS on the settings page.
     */
    public function scripts($hook)
    {
        if ($hook != 'settings_page_wp-cr-mobile/wp-cr-mobile') {
            return;
        }
        $plugin = get_plugin_data(CRMobile::FILE, false, false);
        $version = $plugin['Version'];

        wp_register_style(
            'wp-cr-mobile',
            plugins_url('assets/tabs.css', CRMobile::FILE),
            array(),
            $version
        );
        wp_enqueue_style('wp-cr-mobile');

        wp_enqueue_script(
            'wp-cr-mobile',
            plugins_url('assets/tabs.js', CRMobile::FILE),
            array('jquery'),
            $version,
            false
        );

        wp_enqueue_script(
            'wp-cr-mobile-editors',
            plugins_url('assets/editors.js', CRMobile::FILE),
            array('jquery'),
            $version,
            false
        );

        wp_enqueue_script(
            'wp-cr-mobile-confirmation',
            plugins_url('assets/confirmation.js', CRMobile::FILE),
            array('jquery'),
            $version,
            false
        );
    }
    
    /**
     * Handle the different admin views.
     */
    public static function optionsPage()
    {
        global $wpdb;
        $action = isset($_GET['action']) ? $_GET['action'] : null;
        $id = isset($_GET['id']) ? $_GET['id'] : null;
        $baseUrl = admin_url('/options-general.php');
        $queryArgs = array(
            'page' => CRMobile::PLUGIN_SLUG,
            'id' => ''
        );
        $formUrl = add_query_arg(
            array('page' => CRMobile::PLUGIN_SLUG),
            $baseUrl
        );
        $company_table = $wpdb->prefix . "cr_mobile_companies";
        $reviews_table = $wpdb->prefix . "cr_mobile_reviews";

        switch ($action) {
            case 'new':
                // Only allow admins to add new companies
                if (!current_user_can('manage_options')) {
                    break;
                }
                $data = array(
                    'formUrl' => $formUrl,
                    'id'         => '',
                    'mode'       => 'new',
                    'title'      => __('Add Company', 'wp-cr-mobile'),
                    'moderators' => get_users('role=wp_crmobile _moderator'),
                    'themes'     => CRMobile_Theme::getThemes(),
                    'stars'      => self::getStars(),
                );
                $defaults = array(
                    'company_name' => '',
                    'company_url'  => '',
                    'moderator'    => 0,
                    'star'         => '',
                    'theme'        => 'default',
                    'email'        => false,
                    'intro'        => '',
                    'thanks1'      => '',
                    'thanks2'      => '',
                    'thanks3'      => '',
                    'thanks4'      => '',
                    'thanks5'      => '',
                    'emails1'      => '',
                    'emails2'      => '',
                    'emails3'      => '',
                    'emails4'      => '',
                    'emails5'      => '',
                    'sharing'      => '',
                    'coupon'       => '',
                    'logo'         => '',
                    'service'      => '',
                    'address'      => '',
                    'sms'          => false,
                    'sms_keyword'  => '',
                    'facebook'     => '',
                    'twitter'      => '',
                    'google'       => '',
                );
                $data = array_merge($data, $defaults);

                echo CRMobile_View::render(
                    plugin_dir_path(__FILE__).'../../views/admin-edit.php',
                    $data
                );
                break;
            case 'edit':
                // Only allow admins to edit companies
                if (!current_user_can('manage_options')) {
                    break;
                }

                // Get company to edit
                $query = "SELECT * FROM $company_table WHERE ID = $id";
                $company = $wpdb->get_row($query, OBJECT, 0);

                $data = array(
                    'formUrl' => $formUrl,
                    'id'         => $id,
                    'mode'       => 'edit',
                    'title'      => __('Edit Company', 'wp-cr-mobile'),
                    'moderators' => get_users('role=wp_crmobile _moderator'),
                    'themes'     => CRMobile_Theme::getThemes(),
                    'stars'      => self::getStars(),
                );
                $exclude = unserialize($company->exclude);
                $thanks = unserialize($company->thanks);
                $emails = unserialize($company->emails);
                $social = unserialize($company->social);
                $defaults = array(
                    'company_name' => stripslashes($company->name),
                    'company_url'  => $company->url,
                    'moderator'    => $company->moderator,
                    'star'         => $company->star,
                    'theme'        => $company->theme,
                    'email'        => $exclude['email'],
                    'intro'        => stripslashes($company->intro),
                    'thanks1'      => stripslashes($thanks['thanks_1']),
                    'thanks2'      => stripslashes($thanks['thanks_2']),
                    'thanks3'      => stripslashes($thanks['thanks_3']),
                    'thanks4'      => stripslashes($thanks['thanks_4']),
                    'thanks5'      => stripslashes($thanks['thanks_5']),
                    'emails1'      => stripslashes($emails['emails_1']),
                    'emails2'      => stripslashes($emails['emails_2']),
                    'emails3'      => stripslashes($emails['emails_3']),
                    'emails4'      => stripslashes($emails['emails_4']),
                    'emails5'      => stripslashes($emails['emails_5']),
                    'coupon'       => $company->coupon,
                    'sharing'      => $company->sharing,
                    'logo'         => $company->logo,
                    'service'      => $company->optin_service,
                    'address'      => $company->optin_address,
                    'sms'          => $company->sms,
                    'sms_keyword'  => $company->sms_keyword,
                    'facebook'     => $social['facebook'],
                    'twitter'      => $social['twitter'],
                    'google'       => $social['google'],
                );
                $data = array_merge($data, $defaults);

                echo CRMobile_View::render(
                    plugin_dir_path(__FILE__).'../../views/admin-edit.php',
                    $data
                );
                break;
            case 'moderate':
                // Get company review threshold, and moderator
                $query = "SELECT threshold, moderator, exclude FROM $company_table WHERE ID = $id";
                $company = $wpdb->get_row($query, OBJECT, 0);

                // If not the correct moderator or an administrator, exit
                if (!(get_current_user_id() == $company->moderator
                   or current_user_can('manage_options'))
                ) {
                    break;
                }

                // Check if we need to change a review's published status
                if (isset($_GET['review'])) {
                    $reviewID = $_GET['review'];
                    $set = $_GET['set'];
                    $rows_affected = $wpdb->update(
                        $reviews_table,
                        array(
                            'status' => $set,
                        ),
                        array('ID' => $reviewID)
                    );
                    self::notice('Updated review status.');
                }

                //Check if we shall delete a review
                if (isset($_GET['delete'])) {
                    $deleteID = $_GET['delete'];
                    $query = $wpdb->prepare(
                        "DELETE FROM $reviews_table WHERE ID = %d",
                        $deleteID
                    );
                    $wpdb->query($query);
                    self::notice('Deleted review.');
                }

                // Get list of reviews
                $query = "SELECT * FROM $reviews_table WHERE company_id = $id";
                $reviews = $wpdb->get_results($query, ARRAY_A);

                $data = array(
                    'id'        => $id,
                    'formUrl'   => $formUrl,
                    'baseUrl'   => $baseUrl,
                    'queryArgs' => $queryArgs,
                    'threshold' => $company->threshold,
                    'reviews'   => $reviews,
                    'exclude'   => unserialize($company->exclude)
                );
                echo CRMobile_View::render(
                    plugin_dir_path(__FILE__).'../../views/admin-moderate.php',
                    $data
                );
                break;
            case 'delete':
                // First delete the reviews
                $query = $wpdb->prepare(
                    "DELETE FROM $reviews_table WHERE company_id = %d",
                    $id
                );
                $wpdb->query($query);
                // And then the company
                $query = $wpdb->prepare(
                    "DELETE FROM $company_table WHERE ID = %d",
                    $id
                );
                $wpdb->query($query);
                self::notice('Deleted company.');
                // And then go to default to show the list of companies
            default:
                CRMobile_Admin::catchFormSubmissions();
                $newUrl = add_query_arg(
                    array_merge($queryArgs, array('action' => 'new')),
                    $baseUrl
                );

                // Get list of companies
                if (current_user_can('manage_options')) {
                    $query = "SELECT ID, name FROM $company_table";
                } else {
                    $userID = get_current_user_id();
                    $query = "SELECT ID, name FROM $company_table WHERE moderator = $userID";
                }
                $companies = $wpdb->get_results($query, ARRAY_A);

                $options = get_option('wp_cr_mobile');
                $data = array(
                    'admin'       => current_user_can('manage_options'),
                    'newUrl'      => $newUrl,
                    'baseUrl'     => $baseUrl,
                    'queryArgs'   => $queryArgs,
                    'companies'   => $companies,
                    'formUrl'     => $formUrl,
                    'license_key' => $options['license_key']
                );

                echo CRMobile_View::render(
                    plugin_dir_path(__FILE__).'../../views/admin-list.php',
                    $data
                );
        }
    }

    public static function catchFormSubmissions()
    {
        global $wpdb;
        $company_table = $wpdb->prefix . "cr_mobile_companies";

        // New Company
        if (isset($_POST['submit']) &&
            isset($_POST['new_wp_crmobile _man_nonce']) &&
            wp_verify_nonce($_POST['new_wp_crmobile _man_nonce'], 'new_wp_crmobile _man')
        ) {
            // Only allow admins to add new companies
            if (!current_user_can('manage_options')) {
                return;
            }

            // Handle the logo upload
            add_filter('upload_dir', array( 'CRMobile_Admin', 'uploadDir'));
            $uploadedfile = $_FILES['logo'];
            $upload_overrides = array('test_form' => false);

            $file = wp_handle_upload($_FILES['logo'], $upload_overrides);
            if (isset($file['file']) && !is_wp_error($file)) {
                $logo = $file['url'];
            } else {
                $logo = '';
            }
            remove_filter('upload_dir', array( 'CRMobile_Admin', 'uploadDir'));

            $rows_affected = $wpdb->insert(
                $company_table,
                array(
                    'name'          => esc_attr($_POST['company_name']),
                    'url'           => $_POST['company_url'],
                    'moderator'     => $_POST['moderator'],
                    'star'          => $_POST['star'],
                    'theme'         => $_POST['theme'],
                    'exclude'       => isset($_POST['exclude']) ?
                                       serialize(array('email' => true)) :
                                       serialize(array('email' => false)),
                    'intro'         => $_POST['intro'],
                    'thanks'        => serialize(
                        array(
                            'thanks_1' => $_POST['thanks1'],
                            'thanks_2' => $_POST['thanks2'],
                            'thanks_3' => $_POST['thanks3'],
                            'thanks_4' => $_POST['thanks4'],
                            'thanks_5' => $_POST['thanks5'],
                        )
                    ),
                    'emails'        => serialize(
                        array(
                            'emails_1' => $_POST['emails1'],
                            'emails_2' => $_POST['emails2'],
                            'emails_3' => $_POST['emails3'],
                            'emails_4' => $_POST['emails4'],
                            'emails_5' => $_POST['emails5'],
                        )
                    ),
                    'coupon'        => $_POST['coupon'],
                    'sharing'       => $_POST['sharing'],
                    'logo'          => $logo,
                    'optin_service' => $_POST['service'],
                    'optin_address' => $_POST['address'],
                    'sms'           => isset($_POST['sms']) ? true : false,
                    'sms_keyword'   => $_POST['sms_keyword'],
                    'social'        => serialize(
                        array(
                            'facebook' => $_POST['social_facebook'],
                            'twitter'  => $_POST['social_twitter'],
                            'google'   => $_POST['social_google'],
                        )
                    ),
                )
            );
            self::notice('Company added.');
        }

        // Edit Company
        if (isset($_POST['submit']) &&
            isset($_POST['edit_wp_crmobile _man_nonce']) &&
            wp_verify_nonce($_POST['edit_wp_crmobile _man_nonce'], 'edit_wp_crmobile _man')
        ) {
            // Only allow admins to edit companies
            if (!current_user_can('manage_options')) {
                return;
            }

            // Get company logo
            $id = $_POST['id'];
            $query = "SELECT logo FROM $company_table WHERE ID = $id";
            $company = $wpdb->get_row($query, OBJECT, 0);

            // Handle the logo removal
            if (isset($_POST['remove_logo'])) {
                $upload = wp_upload_dir();

                $logoPath = str_replace(
                    $upload['baseurl'],
                    $upload['basedir'],
                    $company->logo
                );

                unlink($logoPath);
                $company->logo = '';
            }

            // Handle the logo upload
            add_filter('upload_dir', array( 'CRMobile_Admin', 'uploadDir'));
            $uploadedfile = $_FILES['logo'];
            $upload_overrides = array('test_form' => false);

            $file = wp_handle_upload($_FILES['logo'], $upload_overrides);
            if (isset($file['file']) && !is_wp_error($file)) {
                $logo = $file['url'];
            } else {
                $logo = $company->logo;
            }
            remove_filter('upload_dir', array( 'CRMobile_Admin', 'uploadDir'));

            $rows_affected = $wpdb->update(
                $company_table,
                array(
                    'name'          => esc_attr($_POST['company_name']),
                    'url'           => $_POST['company_url'],
                    'moderator'     => $_POST['moderator'],
                    'star'          => $_POST['star'],
                    'theme'         => $_POST['theme'],
                    'exclude'       => isset($_POST['exclude']) ?
                                       serialize(array('email' => true)) :
                                       serialize(array('email' => false)),
                    'intro'         => $_POST['intro'],
                    'thanks'        => serialize(
                        array(
                            'thanks_1' => $_POST['thanks1'],
                            'thanks_2' => $_POST['thanks2'],
                            'thanks_3' => $_POST['thanks3'],
                            'thanks_4' => $_POST['thanks4'],
                            'thanks_5' => $_POST['thanks5'],
                        )
                    ),
                    'emails'        => serialize(
                        array(
                            'emails_1' => $_POST['emails1'],
                            'emails_2' => $_POST['emails2'],
                            'emails_3' => $_POST['emails3'],
                            'emails_4' => $_POST['emails4'],
                            'emails_5' => $_POST['emails5'],
                        )
                    ),
                    'coupon'        => $_POST['coupon'],
                    'sharing'       => $_POST['sharing'],
                    'logo'          => $logo,
                    'optin_service' => $_POST['service'],
                    'optin_address' => $_POST['address'],
                    'sms'           => isset($_POST['sms']) ? true : false,
                    'sms_keyword'   => $_POST['sms_keyword'],
                    'social'        => serialize(
                        array(
                            'facebook' => $_POST['social_facebook'],
                            'twitter'  => $_POST['social_twitter'],
                            'google'   => $_POST['social_google'],
                        )
                    ),
                ),
                array('ID' => $_POST['id'])
            );
            self::notice('Company updated.');
        }

        // Update company review threshold
        if (isset($_POST['submit']) &&
            isset($_POST['mod_wp_crmobile _man_nonce']) &&
            wp_verify_nonce($_POST['mod_wp_crmobile _man_nonce'], 'mod_wp_crmobile _man')
        ) {
            // Get company review threshold, and moderator
            $id = $_POST['id'];
            $query = "SELECT moderator FROM $company_table WHERE ID = $id";
            $company = $wpdb->get_row($query, OBJECT, 0);

            // If not the correct moderator or an administrator, exit
            if (!(get_current_user_id() == $company->moderator
               or current_user_can('manage_options'))
            ) {
                break;
            }

            $rows_affected = $wpdb->update(
                $company_table,
                array(
                    'threshold' => $_POST['threshold'],
                ),
                array('ID' => $_POST['id'])
            );
            self::notice('Updated review threshold.');
        }

        // Update Plugin Options
        if (isset($_POST['submit']) &&
            isset($_POST['opt_wp_crmobile _man_nonce']) &&
            wp_verify_nonce($_POST['opt_wp_crmobile _man_nonce'], 'opt_wp_crmobile _man')
        ) {
            $options = array(
                'version'     => 1,
                'license_key' => trim($_POST['license_key'])
            );
            update_option('wp_cr_mobile', $options);
            self::notice('Updated license key.');
        }
    }

    public static function uploadDir($upload)
    {
        $upload['subdir'] = '/cr-mobile' . $upload['subdir'];
        $upload['path']   = $upload['basedir'] . $upload['subdir'];
        $upload['url']    = $upload['baseurl'] . $upload['subdir'];
        return $upload;
    }

    public static function notice($notice)
    {
        $data = array(
            'notice' => $notice
        );

        echo CRMobile_View::render(
            plugin_dir_path(CRMobile::FILE).'views/notice_admin.php',
            $data
        );
    }

    public static function validLicense()
    {
        $options = get_option('wp_cr_mobile');
        return ($options['license_key'] === self::LICENSE_KEY) ? true : false;
    }

    public static function getStars()
    {
        $starsPath = WP_PLUGIN_DIR.DIRECTORY_SEPARATOR.
            'wp-cr-mobile'.DIRECTORY_SEPARATOR.
            'assets'.DIRECTORY_SEPARATOR.
            'stars'.DIRECTORY_SEPARATOR;
        $stars = self::parseDirectory($starsPath);

        return $stars;
    }

    public static function parseDirectory($dir)
    {
        $results = scandir($dir);
        foreach ($results as $result) {
            if (is_file($dir . '/' . $result)) {
                $displayName = str_replace(array('.png', '.jpg'), '', $result);
                $displayName = str_replace(array('-', '_'), ' ', $displayName);
                $files[$result] = ucwords($displayName);
            }
        }
        return $files;
    }
}
